package com.android.permission;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

import com.android.permission.rom.HuaweiUtils;
import com.android.permission.rom.MeizuUtils;
import com.android.permission.rom.MiuiUtils;
import com.android.permission.rom.OppoUtils;
import com.android.permission.rom.QikuUtils;
import com.android.permission.rom.RomUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @ClassName: FloatPermissionUtil
 * @Desciption: 悬浮窗检测和引导开启工具类
 * @author: yichaohua
 * @date: 2018-03-26
 */
public class FloatPermissionUtil {

    private static final String TAG = "FloatPermissionUtil";

    private static Dialog dialog;

    public static boolean checkPermission(Context context) {
        //6.0 版本之后由于 google 增加了对悬浮窗权限的管理，所以方式就统一了
        if (Build.VERSION.SDK_INT < 23) {
            if (RomUtils.checkIsMiuiRom()) {
                return miuiPermissionCheck(context);
            } else if (RomUtils.checkIsMeizuRom()) {
                return meizuPermissionCheck(context);
            } else if (RomUtils.checkIsHuaweiRom()) {
                return huaweiPermissionCheck(context);
            } else if (RomUtils.checkIs360Rom()) {
                return qikuPermissionCheck(context);
            } else if (RomUtils.checkIsOppoRom()) {
                return oppoROMPermissionCheck(context);
            }
        }
        return commonROMPermissionCheck(context);
    }

    public static boolean huaweiPermissionCheck(Context context) {
        return HuaweiUtils.checkFloatWindowPermission(context);
    }

    public static boolean miuiPermissionCheck(Context context) {
        return MiuiUtils.checkFloatWindowPermission(context);
    }

    public static boolean meizuPermissionCheck(Context context) {
        return MeizuUtils.checkFloatWindowPermission(context);
    }

    public static boolean qikuPermissionCheck(Context context) {
        return QikuUtils.checkFloatWindowPermission(context);
    }

    public static boolean oppoROMPermissionCheck(Context context) {
        return OppoUtils.checkFloatWindowPermission(context);
    }

    public static boolean commonROMPermissionCheck(Context context) {
        //最新发现魅族6.0的系统这种方式不好用，天杀的，只有你是奇葩，没办法，单独适配一下
        if (RomUtils.checkIsMeizuRom()) {
            return meizuPermissionCheck(context);
        } else {
            Boolean result = true;
            if (Build.VERSION.SDK_INT >= 23) {
                try {
                    Class clazz = Settings.class;
                    Method canDrawOverlays = clazz.getDeclaredMethod("canDrawOverlays", Context.class);
                    result = (Boolean) canDrawOverlays.invoke(null, context);
                } catch (Exception e) {
                    Log.e(TAG, Log.getStackTraceString(e));
                }
            }
            return result;
        }
    }

    public static void applyPermission(boolean noShowConfirm,Context context) {
        if (Build.VERSION.SDK_INT < 23) {
            if (RomUtils.checkIsMiuiRom()) {
                miuiROMPermissionApply(noShowConfirm,context);
            } else if (RomUtils.checkIsMeizuRom()) {
                meizuROMPermissionApply(noShowConfirm,context);
            } else if (RomUtils.checkIsHuaweiRom()) {
                huaweiROMPermissionApply(noShowConfirm,context);
            } else if (RomUtils.checkIs360Rom()) {
                ROM360PermissionApply(noShowConfirm,context);
            } else if (RomUtils.checkIsOppoRom()) {
                oppoROMPermissionApply(noShowConfirm,context);
            }
        }
        commonROMPermissionApply(noShowConfirm,context);
    }

    public static void ROM360PermissionApply(boolean noShowConfirm,final Context context) {
        if(noShowConfirm){
            QikuUtils.applyPermission(context);
        }else {
            showConfirmDialog(context, new OnConfirmResult() {
                @Override
                public void confirmResult(boolean confirm) {
                    if (confirm) {
                        QikuUtils.applyPermission(context);
                    } else {
                        Log.e(TAG, "ROM:360, user manually refuse OVERLAY_PERMISSION");
                    }
                }
            });
        }

    }

    public static void huaweiROMPermissionApply(boolean noShowConfirm,final Context context) {
        if(noShowConfirm){
            HuaweiUtils.applyPermission(context);
        }else {
            showConfirmDialog(context, new OnConfirmResult() {
                @Override
                public void confirmResult(boolean confirm) {
                    if (confirm) {
                        HuaweiUtils.applyPermission(context);
                    } else {
                        Log.e(TAG, "ROM:huawei, user manually refuse OVERLAY_PERMISSION");
                    }
                }
            });
        }

    }

    public static void meizuROMPermissionApply(boolean noShowConfirm,final Context context) {
        if(noShowConfirm){
            MeizuUtils.applyPermission(context);
        }else {
            showConfirmDialog(context, new OnConfirmResult() {
                @Override
                public void confirmResult(boolean confirm) {
                    if (confirm) {
                        MeizuUtils.applyPermission(context);
                    } else {
                        Log.e(TAG, "ROM:meizu, user manually refuse OVERLAY_PERMISSION");
                    }
                }
            });
        }

    }

    public static void miuiROMPermissionApply(boolean noShowConfirm,final Context context) {
        if(noShowConfirm){
            MiuiUtils.applyMiuiPermission(context);
        }else {
            showConfirmDialog(context, new OnConfirmResult() {
                @Override
                public void confirmResult(boolean confirm) {
                    if (confirm) {
                        MiuiUtils.applyMiuiPermission(context);
                    } else {
                        Log.e(TAG, "ROM:miui, user manually refuse OVERLAY_PERMISSION");
                    }
                }
            });
        }
    }

    public static void oppoROMPermissionApply(boolean noShowConfirm,final Context context) {
        if(noShowConfirm){
            OppoUtils.applyOppoPermission(context);
        }else {
            showConfirmDialog(context, new OnConfirmResult() {
                @Override
                public void confirmResult(boolean confirm) {
                    if (confirm) {
                        OppoUtils.applyOppoPermission(context);
                    } else {
                        Log.e(TAG, "ROM:miui, user manually refuse OVERLAY_PERMISSION");
                    }
                }
            });
        }

    }

    /**
     * 通用 rom 权限申请
     */
    public static void commonROMPermissionApply(boolean noShowConfirm,final Context context) {
        //这里也一样，魅族系统需要单独适配
        if (RomUtils.checkIsMeizuRom()) {
            meizuROMPermissionApply(noShowConfirm,context);
        } else {
            if (Build.VERSION.SDK_INT >= 23) {
                if(noShowConfirm){
                    try {
                        commonROMPermissionApplyInternal(context);
                    } catch (Exception e) {
                        Log.e(TAG, Log.getStackTraceString(e));
                    }
                }else {
                    showConfirmDialog(context, new OnConfirmResult() {
                        @Override
                        public void confirmResult(boolean confirm) {
                            if (confirm) {
                                try {
                                    commonROMPermissionApplyInternal(context);
                                } catch (Exception e) {
                                    Log.e(TAG, Log.getStackTraceString(e));
                                }
                            } else {
                                Log.d(TAG, "user manually refuse OVERLAY_PERMISSION");
                                //需要做统计效果
                            }
                        }
                    });
                }

            }
        }

    }

    public static void commonROMPermissionApplyInternal(Context context) throws NoSuchFieldException, IllegalAccessException {
        Class clazz = Settings.class;
        Field field = clazz.getDeclaredField("ACTION_MANAGE_OVERLAY_PERMISSION");

        Intent intent = new Intent(field.get(null).toString());
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }

    public static void showConfirmDialog(Context context, OnConfirmResult result) {
        showConfirmDialog(context, "您的手机没有授予悬浮窗权限，请开启后再试", result);
    }

    public static void showConfirmDialog(Context context, String message, final OnConfirmResult result) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }

        dialog = new AlertDialog.Builder(context).setCancelable(true)
                .setCancelable(false)
                .setTitle("")
                .setMessage(message)
                .setPositiveButton("现在去开启",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.confirmResult(true);
                                dialog.dismiss();
                            }
                        }).setNegativeButton("暂不开启",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.confirmResult(false);
                                dialog.dismiss();
                            }
                        }).create();
        dialog.show();
    }

    private interface OnConfirmResult {
        void confirmResult(boolean confirm);
    }
}
